package com.apes.fn.scm.retailOrder.service.account.retailReturn;

import com.apes.fn.scm.retailOrder.service.account.RetailReturnVoucher;
import com.apes.fn.scm.retailReturn.RetailReturn;
import com.apes.scm.account.account.model.AccountingMethod;
import com.apes.scm.account.account.model.InventoryMode;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherItem;
import com.apes.scm.voucher.service.BusinessType;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author wuq
 * @Date 2021-11-22
 */
@RetailReturnAccount(value = "returnWithoutOrder", name = "零售无单退货生成销售退回凭证")
@Service
public class RetailReturnWithoutOrderVoucherService implements RetailReturnVoucher {

    @Override
    public Voucher process(RetailReturn retailReturn) {
        Voucher voucher = new Voucher();
        voucher.setReturned(true);
        voucher.setBusinessType(BusinessType.SALE_RETURN);
        voucher.setInventoryMode(InventoryMode.IM_OWN);     //设置库存模式：自有经销
        voucher.setAccountingMethod(AccountingMethod.AM_PURCHASE);  // 核算方式：采购

        // 主表信息
        voucher.setCompany(retailReturn.getDept().getCompany());
        voucher.setDept(retailReturn.getDept());
        voucher.setClerk(retailReturn.getClerk()); //业务员
        voucher.setPartner(retailReturn.getCustomer());

        voucher.setScene(retailReturn.getScene());
        voucher.setOrigin(retailReturn.getId());
        voucher.setOriginBusinessType(retailReturn.getInnerBusinessType());
        voucher.setSource(retailReturn.getId());
        voucher.setSourceBusinessType(retailReturn.getInnerBusinessType());

        // 明细处理
        voucher.setVoucherItems(getItems(retailReturn, voucher));
        return voucher;
    }


    private Set<VoucherItem> getItems(RetailReturn saleReturn, Voucher voucher) {
        Set<VoucherItem> voucherItems = new HashSet();
        saleReturn.getSaleItems().forEach(
                saleReturnItem -> {
                    VoucherItem voucherItem = new VoucherItem();
                    voucherItem.setOwner(saleReturnItem.getOwner());

                    voucherItem.setProduct(saleReturnItem.getProduct());
                    voucherItem.setTax(saleReturnItem.getTax());
                    voucherItem.setUom(saleReturnItem.getUom());

                    // 设置为销售的单位以及单价(退货价格设置为负数)
                    voucherItem.setProductQty(-1.00 * saleReturnItem.getProductUomQty());
                    voucherItem.setPriceUnit(saleReturnItem.getPriceUnit());
                    voucherItem.setDiscount(-1.00 * Math.abs(saleReturnItem.getDiscountAmount()));

                    voucherItem.setSupplier(saleReturnItem.getSupplier());
                    voucherItem.setOriginItemId(saleReturnItem.getId());
                    voucherItem.setSourceItemId(String.valueOf(saleReturnItem.getId()));
                    voucherItems.add(voucherItem);
                });
        return voucherItems;
    }

}
